package com.telenav.snowsweeper.renderer;

import java.util.Vector;

import com.telenav.snowsweeper.data.DisplayUtil;
import com.telenav.snowsweeper.data.Edge;
import com.telenav.snowsweeper.data.EdgeMap;
import com.telenav.snowsweeper.data.Point;

import android.graphics.Rect;
import android.os.SystemClock;

public class MapEdgeBuilder {
	private EdgeMap edgeMap;
	
	public MapEdgeBuilder(EdgeMap edgeMap) {
		this.edgeMap = edgeMap;
	}
	
	public void build(MapEdgeRenderer.RendererParams params) {
		long timeStamp = SystemClock.uptimeMillis();
		params.edgesOnScreen.clear();
		Rect clip = getClip(params);
		edgeMap.clipEdges(clip, params.edgesOnScreen);
		
		Point pnt;
		for (Edge edge : params.edgesOnScreen) {
			pnt = edge.getBegin();
			if (pnt.getScreenXY(timeStamp) == null) {
				Util.mapPoint2ScreenPoint(pnt, clip, params.scaleX, params.scaleY, timeStamp);
			}
			pnt = edge.getEnd();
			if (pnt.getScreenXY(timeStamp) == null) {
				Util.mapPoint2ScreenPoint(pnt, clip, params.scaleX, params.scaleY, timeStamp);
			}
		}
		params.timeStamp = timeStamp;
		
		int width = Util.mapDist2Screen(DisplayUtil.EDGE_WIDTH, params.scaleX);		// FIXME
		if (width > DisplayUtil.EDGE_MAX_WIDTH_PX)
			width = DisplayUtil.EDGE_MAX_WIDTH_PX;
		else if (width < DisplayUtil.EDGE_MIN_WIDTH_PX)
			width = DisplayUtil.EDGE_MIN_WIDTH_PX;
		params.edgeWidth = width;
	}
	
	public Rect getClip(MapEdgeRenderer.RendererParams params) {
		Rect r = new Rect();
		int spanX = Util.screenDist2Map(Util.canvasWidth, params.scaleX) + 1;
		int spanY = Util.screenDist2Map(Util.canvasHeight, params.scaleY) + 1;
		r.left = params.centerX - (spanX >> 1);
		r.right = r.left + spanX;
		r.top = params.centerY - (spanY >> 1);
		r.bottom = r.top + spanY;
		return r;
	}
}
